//
//  ChangePSDController.m
//  operativeSide-2.0
//
//  Created by 王春程 on 2016/12/15.
//  Copyright © 2016年 王春程. All rights reserved.
//

#import "ChangePSDController.h"
#import "VerifyController.h"


@interface ChangePSDController ()<UITextFieldDelegate>
@property (assign, nonatomic)        BOOL isFirst;
@property (strong, nonatomic)        LogInManager *manager;
@property (weak, nonatomic) IBOutlet UIImageView *backImageView;

@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField2;
@property (weak, nonatomic) IBOutlet UIButton *confirmBtn;

@end

@implementation ChangePSDController

- (void)viewDidLoad {
    [super viewDidLoad];
    WS(weakSelf);
    self.manager = [LogInManager sharedManager];
    [self registerForKeyboardNotifications];
    self.confirmBtn.enabled = NO;
    self.passwordTextField.delegate = self;
    self.passwordTextField2.delegate = self;
    
    self.passwordTextField.attributedPlaceholder = [[NSMutableAttributedString alloc]initWithString:@"请输入新密码" attributes:@{NSForegroundColorAttributeName:RGB(204, 204, 204)}];
    self.passwordTextField2.attributedPlaceholder = [[NSMutableAttributedString alloc]initWithString:@"请再次输入新密码" attributes:@{NSForegroundColorAttributeName:RGB(204, 204, 204)}];
    
    
    
    RACSignal *passWordSignal =
    [self.passwordTextField.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        
        return @(value.length > 5 && value.length < 16);
    }];
    
    RACSignal *passWordSignal2 =
    [self.passwordTextField2.rac_textSignal map:^id _Nullable(NSString * _Nullable value) {
        
        return @(value.length > 5 && value.length < 16);
    }];
    
    RAC(self.confirmBtn,enabled) =
    [RACSignal combineLatest:@[passWordSignal,passWordSignal2] reduce:^id _Nullable(NSNumber *pasIsVal,NSNumber *pasIsVal2){
        return @([pasIsVal boolValue] && [pasIsVal2 boolValue]);
    }];
    
    [[self.confirmBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if(self.passwordTextField.text != self.passwordTextField2.text) {
            [weakSelf.view makeToast:@"两次密码输入不一致,请重新输入" duration:1.5 position:@"center"];
        } else {
            [[weakSelf reCodeSignal] subscribeNext:^(NSNumber *value) {
                if([value boolValue]) {
                    [weakSelf.view makeToast:@"密码修改成功" duration:1.0 position:@"center"];
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                        [weakSelf.navigationController pushViewController:[VerifyController new] animated:YES];
                        NSLog(@"navgation push");
                    });
                } else {
                    [weakSelf.view makeToast:@"修改密码失败，请重新提交" duration:1.0 position:@"center"];
                    
                }
            }];
        }
    }];
}


- (RACSignal *)reCodeSignal
{
    @weakify(self)
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self)
        
        [self.manager reCodePasswordWithPasswrod:self.passwordTextField.text
                   complete:^(BOOL isSuccess) {
                       [subscriber sendNext:@(isSuccess)];
                       [subscriber sendCompleted];
        }];
        return nil;
        
    }];
}

- (void)registerForKeyboardNotifications

{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

//实现当键盘出现的时候计算键盘的高度大小。用于输入框显示位置
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    CGFloat duration = [aNotification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    CGRect frame = [aNotification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    WS(ws);
    if (self.isFirst == YES) {
        CGRect rect = ws.view.bounds;
        rect.origin.y = 286 + 35 - frame.origin.y;
        if (rect.origin.y > 0) {
            [UIView animateWithDuration:duration animations:^{
                NSLog(@"%f",rect.origin.y);
                ws.view.bounds = rect;
            }];
        }
        
    }else {
        
        CGRect rect = ws.view.bounds;
        rect.origin.y = 286 + 70 - frame.origin.y;
        if (rect.origin.y > 0) {
            [UIView animateWithDuration:duration animations:^{
                ws.view.bounds = rect;
            }];
        }
    }
}

//当键盘隐藏的时候
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    WS(ws);
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = ws.view.bounds;
        rect.origin.y = 0;
        ws.view.bounds = rect;
    }];
}

#pragma mark -_- TextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if(textField == self.passwordTextField) {
        
        self.isFirst = YES;

        
    } else {
        
        self.isFirst = NO;

    }
    
    return YES;
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{

    [self.passwordTextField resignFirstResponder];
    [self.passwordTextField2 resignFirstResponder];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
